package todo.client;

import todo.shared.FieldVerifier;
import todo.shared.TodoVO;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

import core.todo.dao.TodoDAO;
import core.todo.domain.Todo;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class TodoGWeb implements EntryPoint {
	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";

	// panel for showing selected contact
	// table for displaying contact data
	// button for creating new contact

	/**
	 * Create a remote service proxy to talk to the server-side TodoService.
	 * 1) Read Todos
	 * 1.2) Read specific Todo
	 * 2) Create new Todo
	 * 3) Update existing Todo
	 * 4) Delete Todo 
	 */
	final TodoServiceAsync todoService = GWT
		.create(TodoService.class);
	private final GreetingServiceAsync greetingService = GWT
			.create(GreetingService.class);
	
	FlexTable tblTodos = new FlexTable();
	Label lblSelected = new Label("[selected text goes here]");
	final DeleteClickHandler deleteClickHandler = new DeleteClickHandler(this);
	final AddClickHandler addClickHandler = new AddClickHandler(this);
	final Button btnAdd = new Button("Add", addClickHandler);
	
	final ClickHandler selectClickHandler = new ClickHandler() {
		@Override
		public void onClick(ClickEvent event) {
			// find 
			Label lbl = (Label) event.getSource();
			Long id = new Long(lbl.getTitle());
			lblSelected.setText("bingo: " + id);	
		}
	};
	
	
	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		//createTestData();
		tblTodos.setBorderWidth(1);
		tblTodos.setTitle("Todos");
		
		RootPanel.get("lblSelected").add(lblSelected);
		RootPanel.get("tblTodos").add(tblTodos);
		RootPanel.get("btnAdd").add(btnAdd);
		
		renderTodoTable();
		
	}

	
	 void createTestData() {
		System.out.println("Create test data...");
		TodoVO newInstance = new TodoVO(null, "Sample Title", "Just some test data", new java.util.Date(), true); 
		todoService.create(newInstance, new AsyncCallback<Void>(){

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				caught.printStackTrace();
			}

			@Override
			public void onSuccess(Void result) {
				System.out.println("createTestData: onSuccess");
			}});
		System.out.println("Create test data compete.");
	}
	
	void renderTodoTable() {
		
		todoService.findAll(new AsyncCallback<TodoVO[]>(){

			@Override
			public void onFailure(Throwable caught) {
				System.out.println("getAllTodos(): onFailure: " + caught);
				
			}

			@Override
			public void onSuccess(TodoVO[] todos) {
				System.out.println("getAllTodos(): onSuccess: " + todos.length);
				tblTodos.removeAllRows();
				if (todos != null) {
					for (int i = 0; i < todos.length; i++) {
						String id = String.valueOf(todos[i].getId());
						
						Label lbl = new Label("X");
						lbl.setTitle(id);
						lbl.addClickHandler(deleteClickHandler);
						tblTodos.setWidget(i, 0, lbl);
						
						Label lblTitle = new Label(todos[i].getTitle());
						lblTitle.setTitle(id);
						lblTitle.addClickHandler(selectClickHandler);
						tblTodos.setWidget(i, 1, lblTitle);
						
						tblTodos.setText(i, 2, String.valueOf(todos[i].getDueDt()));
						
						tblTodos.setText(i, 3, String.valueOf(todos[i].getComplete()));			
					}
				} else {
					System.out.println("todos: " + todos);
				}
			}});
	}
	/**
	 * This was the entry point method.
	 */
//	public void onModuleLoadOld() {
//		
//		
//		final Button sendButton = new Button("Send");
//		final TextBox nameField = new TextBox();
//		nameField.setText("GWT User");
//		final Label errorLabel = new Label();
//
//		// We can add style names to widgets
//		sendButton.addStyleName("sendButton");
//
//		// Add the nameField and sendButton to the RootPanel
//		// Use RootPanel.get() to get the entire body element
//		RootPanel.get("nameFieldContainer").add(nameField);
//		RootPanel.get("sendButtonContainer").add(sendButton);
//		RootPanel.get("errorLabelContainer").add(errorLabel);
//
//		// Focus the cursor on the name field when the app loads
//		nameField.setFocus(true);
//		nameField.selectAll();
//
//		// Create the popup dialog box
//		final DialogBox dialogBox = new DialogBox();
//		dialogBox.setText("Remote Procedure Call");
//		dialogBox.setAnimationEnabled(true);
//		final Button closeButton = new Button("Close");
//		// We can set the id of a widget by accessing its Element
//		closeButton.getElement().setId("closeButton");
//		final Label textToServerLabel = new Label();
//		final HTML serverResponseLabel = new HTML();
//		VerticalPanel dialogVPanel = new VerticalPanel();
//		dialogVPanel.addStyleName("dialogVPanel");
//		dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
//		dialogVPanel.add(textToServerLabel);
//		dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
//		dialogVPanel.add(serverResponseLabel);
//		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
//		dialogVPanel.add(closeButton);
//		dialogBox.setWidget(dialogVPanel);
//
//		// Add a handler to close the DialogBox
//		closeButton.addClickHandler(new ClickHandler() {
//			public void onClick(ClickEvent event) {
//				dialogBox.hide();
//				sendButton.setEnabled(true);
//				sendButton.setFocus(true);
//			}
//		});
//
//		// Create a handler for the sendButton and nameField
//		class MyHandler implements ClickHandler, KeyUpHandler {
//			/**
//			 * Fired when the user clicks on the sendButton.
//			 */
//			public void onClick(ClickEvent event) {
//				sendNameToServer();
//			}
//
//			/**
//			 * Fired when the user types in the nameField.
//			 */
//			public void onKeyUp(KeyUpEvent event) {
//				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
//					sendNameToServer();
//				}
//			}
//
//			/**
//			 * Send the name from the nameField to the server and wait for a response.
//			 */
//			private void sendNameToServer() {
//				// First, we validate the input.
//				errorLabel.setText("");
//				String textToServer = nameField.getText();
//				if (!FieldVerifier.isValidName(textToServer)) {
//					errorLabel.setText("Please enter at least four characters");
//					return;
//				}
//
//				// Then, we send the input to the server.
//				sendButton.setEnabled(false);
//				textToServerLabel.setText(textToServer);
//				serverResponseLabel.setText("");
//				greetingService.greetServer(textToServer,
//						new AsyncCallback<String>() {
//							public void onFailure(Throwable caught) {
//								// Show the RPC error message to the user
//								dialogBox
//										.setText("Remote Procedure Call - Failure");
//								serverResponseLabel
//										.addStyleName("serverResponseLabelError");
//								serverResponseLabel.setHTML(SERVER_ERROR);
//								dialogBox.center();
//								closeButton.setFocus(true);
//							}
//
//							public void onSuccess(String result) {
//								dialogBox.setText("Remote Procedure Call");
//								serverResponseLabel
//										.removeStyleName("serverResponseLabelError");
//								serverResponseLabel.setHTML(result);
//								dialogBox.center();
//								closeButton.setFocus(true);
//							}
//						});
//			}
//		}
//
//		// Add a handler to send the name to the server
//		MyHandler handler = new MyHandler();
//		sendButton.addClickHandler(handler);
//		nameField.addKeyUpHandler(handler);
//	}

}
